﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Parameters;
using ShopB2C.ViewModels;

namespace ShopB2C.Helper {
    /// <summary>
    /// HtmlHelper 扩展类
    /// </summary>  
    public static class HtmlExtend {

        #region 其它

        /// <summary>
        /// 返回是否允许用户编辑或删除自己的咨询
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="ce">ConsultEntity</param>
        /// <param name="pageIndex">当前页码</param>
        /// <returns>string</returns>
        public static string AllowUserOperationConsult(this HtmlHelper helper, ConsultEntity ce, int pageIndex) {
            const string input = @"<input type=""button"" value=""{0}"" onclick=""$c.go('{1}','{2}');"" />";
            string result = string.Empty;
            UserEntity user = helper.ViewData["User"] as UserEntity;
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            if (helper.ViewContext.HttpContext.User.Identity.IsAuthenticated) {
                if (user.Uid == ce.Uid) {
                    if (!ce.IsAudit && ce.AddDate.AddHours(1) >= DateTime.Now) {
                        result += string.Format(input, "删  除",
                            url.Action("ConsultDelete", "Consult", new {
                                productId = ce.ProductId,
                                consultId = ce.ConsultId
                            }), "确定要删除该评论吗?");
                        result += string.Format(input, "编  辑",
                            url.Action("ConsultList", "Consult", new {
                                productId = ce.ProductId,
                                consultId = ce.ConsultId,
                                pageIndex = pageIndex
                            }), string.Empty);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 返回是否允许用户编辑或删除自己的评论
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="ce">CommentEntity</param>
        /// <returns>string</returns>
        public static string AllowUserOperationComment(this HtmlHelper helper, CommentEntity ce) {
            const string input = @"<input type=""button"" value=""{0}"" onclick=""$c.go('{1}','{2}');"" />";
            string result = string.Empty;
            UserEntity user = helper.ViewData["User"] as UserEntity;
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            if (helper.ViewContext.HttpContext.User.Identity.IsAuthenticated) {
                if (user.Uid == ce.Uid) {
                    if (ce.ReplyNum == 0 && ce.AddDate.AddHours(1) >= DateTime.Now) {
                        result += string.Format(input, "删  除",
                            url.Action("CommentDelete", "Comment", new {
                                productId = ce.ProductId,
                                commentId = ce.CommentId
                            }), "确定要删除该评论吗?");
                        result += string.Format(input, "编  辑",
                            url.Action("CommentEdit", "Comment", new {
                                productId = ce.ProductId,
                                commentId = ce.CommentId
                            }), string.Empty);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 获得间隔行的 CSS className
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="index">行索引</param>
        /// <param name="className">CSS 类名</param>
        /// <returns>string</returns>
        public static string AlternateRowClass(this HtmlHelper helper, int index, string className) {
            return index % 2 == 0 ? className : string.Empty;
        }
        /// <summary>
        /// 输出热门搜索关键字代码
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <returns>html string</returns>
        public static string EchoSearchHotKeys(this HtmlHelper helper) {
            const string a = "<a href=\"{0}\">{1}</a>&nbsp;";

            string hotKeys = ConfigHelper.GetValue(ConfigNodeNames.Search, "hotkeys");
            StringBuilder sb = new StringBuilder();
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);

            if (!string.IsNullOrEmpty(hotKeys)) {
                foreach (string s in hotKeys.Split(',')) {
                    sb.AppendFormat(a, url.Action("Search", "Product", new { Key = s }), s);
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 输出帮助中心代码
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <returns>html string</returns>
        public static string EchoHelpCenterHtml(this HtmlHelper helper) {
            const string img = "<img src=\"{0}\" alt=\"{1}\" />";
            const string a = "<a href=\"{0}\" target=\"_blank\">{1}</a>";

            StringBuilder sb = new StringBuilder();
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            List<HelpTypeEntity> listTypes = helper.ViewData["HelpType"] as List<HelpTypeEntity>;
            List<HelpSectionEntity> listSections = helper.ViewData["HelpSection"] as List<HelpSectionEntity>;

            foreach (HelpTypeEntity hte in listTypes) {
                sb.AppendFormat("<dl{1}><dt>{0}</dt>",
                    string.IsNullOrEmpty(hte.Photo)
                        ? hte.Name
                        : string.Format(img,
                            url.Content("~/OtherPictures/" + hte.Photo),
                            hte.Name), listTypes.Last() == hte ? " class=\"Help_b5\"" : string.Empty);
                foreach (HelpSectionEntity hse in listSections.Where(s => {
                    return s.TypesId == hte.TypesId;
                })) {
                    sb.AppendFormat("<dd>{0}</dd>",
                        string.Format(a, hse.IsExLink && !string.IsNullOrEmpty(hse.ExLinkUrl)
                            ? hse.ExLinkUrl
                            : url.Action("View", "Help", new { id = hse.SectionsId }),
                        hse.Title));
                }
                sb.Append("</dl>");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 输出 SiteMapPath
        /// </summary>
        /// <param name="html">HtmlHelper</param>
        /// <returns>string</returns>
        public static string SiteMapPath(this HtmlHelper html) {
            List<string> urls = (List<string>)html.ViewData["SiteMapPath"];
            const string em = "<em>></em>";
            StringBuilder sb = new StringBuilder(urls.Count);

            foreach (string s in urls) {
                sb.Append(s);
                if (s != urls.Last()) {
                    sb.Append(em);
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 输出产品分类和特性搜索代码
        /// </summary>
        /// <param name="html">HtmlHelper</param>
        /// <returns>html string</returns>
        public static string EchoProductSearch(this HtmlHelper html) {
            const string a = "<a href=\"{0}\">{1}</a>";

            StringBuilder sb = new StringBuilder();
            ProductViewModel m = (ProductViewModel)html.ViewData.Model;
            UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);

            if (m.Classify.ParentClassifyId != 0 & m.Classify.Childs < 1) {
                sb.Append("<div class='f'>");
                sb.AppendFormat("<h1>{0} - 属性筛选</h1>", m.Classify.Title);

                int i = 0;
                bool flag = false;
                string link;
                foreach (var item in m.PropertyFilter) {
                    sb.AppendFormat("<dl class=\"dlProperty{0}\">", i == 0 ? " dlPropertyFirst" : string.Empty);
                    sb.Append("<dt>");
                    sb.AppendFormat("{0}:", item.Key);
                    sb.Append("</dt>");
                    sb.Append("<dd>");

                    ProductParam ppAll = m.ProductParams.Clone();
                    link = string.Format(a, url.Action("ProductList", new {
                        productParams = ppAll.ClearPropertyVal(i)
                    }), "全部");
                    sb.Append(m.ProductParams.PropertyVal[i] == 0
                        ? string.Format("<em>{0}</em>", link)
                        : link);

                    foreach (var innerItem in item.Value) {
                        ProductParam ppItem = m.ProductParams.Clone();
                        flag = ppItem.PropertyVal[i] != innerItem.PropertyValId;
                        if (flag) {
                            ppItem.PropertyVal[i] = innerItem.PropertyValId;
                        }

                        link = string.Format(a, url.Action("ProductList", new {
                            productParams = ppItem.ToString()
                        }), innerItem.PropertyValue);
                        sb.Append(flag ? link : string.Format("<em>{0}</em>", link));
                    }

                    sb.Append("</dd>");
                    sb.Append("</dl>");
                    i++;
                }
                sb.Append("</div>");
            }
            else {
                sb.Append("<div class='f'>");

                sb.Append(string.Format("<h1>{0} - 分类筛选</h1>", m.Classify.Title));
                sb.Append("<dl class=\"dlClassify\">");
                sb.Append("<dt>");
                sb.Append("分类名称:");
                sb.Append("</dt>");
                sb.AppendFormat("<dd>");

                sb.AppendFormat("<em>{0}</em>",
                    string.Format(a, url.Action("ProductList", new {
                        productParams = m.ProductParams.ToString()
                    }), "全部"));
                foreach (ClassifyEntity item in m.ChildClassify) {
                    ProductParam ppClassify = m.ProductParams.Clone();
                    ppClassify.Classify.Add(item.ClassifyId);
                    sb.AppendFormat(a,
                        url.Action("ProductList", new { productParams = ppClassify.ToString() }),
                        item.Title);
                }

                sb.Append("</dd>");
                sb.Append("</dl>");
                sb.Append("</div>");
            }

            return sb.ToString();
        }
        /// <summary>
        /// 构造商品搜索页的 URL
        /// </summary>
        /// <param name="html">HtmlHelper</param>
        /// <param name="key">字典 key</param>
        /// <param name="value">指定的值</param>
        /// <returns>string</returns>
        public static string CreateSearchUrl(this HtmlHelper html, string key, object value) {
            ProductViewModel vm = (ProductViewModel)html.ViewData.Model;
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("ClassifyId", vm.Search.ClassifyId);
            d.Add("BrandId", vm.Search.BrandId);
            d.Add("View", (int)vm.Search.ShowType);
            d.Add("SortF", (int)vm.Search.SortIndex);
            d.Add("SortD", 1);
            d.Add("Price", string.Format("{0}-{1}", vm.Search.PriceFrom, vm.Search.PriceTo));
            d[key] = value;

            return new UrlHelper(html.ViewContext.RequestContext).Action("Search", "Product", new {
                Key = vm.Search.Key,
                ClassifyId = d["ClassifyId"],
                BrandId = d["BrandId"],
                View = d["View"],
                SortF = d["SortF"],
                SortD = d["SortD"],
                Price = d["Price"],
                PageIndex = vm.Search.PageIndex
            });
        }
        /// <summary>
        /// 构造商品搜索页价格升序的 URL
        /// </summary>
        /// <param name="html">HtmlHelper</param>
        /// <returns>string</returns>
        public static string CreateSearchPriceASCUrl(this HtmlHelper html) {
            ProductViewModel vm = (ProductViewModel)html.ViewData.Model;
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("ClassifyId", vm.Search.ClassifyId);
            d.Add("BrandId", vm.Search.BrandId);
            d.Add("View", (int)vm.Search.ShowType);
            d.Add("SortF", 3);
            d.Add("SortD", -1);
            d.Add("Price", string.Format("{0}-{1}", vm.Search.PriceFrom, vm.Search.PriceTo));

            return new UrlHelper(html.ViewContext.RequestContext).Action("Search", "Product", new {
                Key = vm.Search.Key,
                ClassifyId = d["ClassifyId"],
                BrandId = d["BrandId"],
                View = d["View"],
                SortF = d["SortF"],
                SortD = d["SortD"],
                Price = d["Price"],
                PageIndex = vm.Search.PageIndex
            });
        }

        #endregion

        #region 分类

        /// <summary>
        /// 当前分类是否是最后一级分类
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="childs">子数量</param>
        /// <returns>string</returns>
        public static string ShowClassSymbol(this HtmlHelper helper, ClassifyEntity ce) {            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            string img = string.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" />",
               url.Content(string.Format("~/Css/Manager/Images/{0}",
               ce.Childs == 0 ? "Open.gif " : "Close.gif ")),
               ce.Childs == 0 ? "无子分类" : "有子分类");
            string a = string.Format("<a href=\"{0}\">{1} {2}</a>",
                url.Action("ClassifyList", new {
                    classifyParams = new ClassifyParam() {
                        ModuleKey = ce.ModuleKey,
                        ParentClassifyId = ce.ClassifyId
                    }.ToString()
                }), ((ClassifyViewModel)helper.ViewData.Model).IsAllowHasChild ? img : string.Empty,
                ce.Title);
            return a;
        } 
        /// <summary>
        /// 显示当前分类的所有父辈级分类
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="cvm">ClassifyViewModel</param>
        /// <returns>string</returns>
        public static string ShowAllParentClassify(this HtmlHelper helper, ClassifyViewModel cvm) {

            string link = string.Empty;
            string html = "<b class=\"colorRed\">父辈分类: </b>";
            string button = "<input type=\"button\" value=\"{0}\" onclick=\"$c.go('{1}');\" />";
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);

            if (cvm.Classify.ClassifyId > 0) {
                link = url.Action("ClassifyList", new {
                    classifyParams = new ClassifyParam() {
                        ModuleKey = cvm.ClassifyParams.ModuleKey,
                        ParentClassifyId = 0
                    }
                });
                html += string.Format(button, cvm.ModuleName, link);

                if (cvm.PathList != null) {
                    foreach (ClassifyEntity ce in cvm.PathList) {
                        link = url.Action("ClassifyList", new {
                            classifyParams = new ClassifyParam() {
                                ModuleKey = ce.ModuleKey,
                                ParentClassifyId = ce.ClassifyId
                            }
                        });
                        html += " > ";
                        html += string.Format(button, ce.Title, link);
                    }
                }
            }
            else {
                html += "<input type=\"button\" value=\"已经处于顶级分类\" disabled=\"disabled\" />";
            }
            return html;
        }

        #endregion

        #region 跳转按钮

        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value, string url) {
            return UrlButton(helper, value, url, null, null, false);
        }
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <param name="isDisabled">是否禁用</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value,
            string url, bool isDisabled) {
            return UrlButton(helper, value, url, null, null, isDisabled);
        }
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <param name="className">CSS 类名</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value,
            string url, string className) {
            return UrlButton(helper, value, url, className, null, false);
        }
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <param name="className">CSS 类名</param>
        /// <param name="isDisabled">是否禁用</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value,
            string url, string className, bool isDisabled) {
            return UrlButton(helper, value, url, className, null, isDisabled);
        }
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <param name="className">CSS 类名</param>
        /// <param name="confirmInfo">确认操作弹出信息</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value,
            string url, string className, string confirmInfo) {
            return UrlButton(helper, value, url, className, confirmInfo, false);
        }
        /// <summary>
        /// 跳转按钮
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="value">按钮文字</param>
        /// <param name="url">Url 地址</param>
        /// <param name="className">CSS 类名</param>
        /// <param name="confirmInfo">确认操作弹出信息</param>
        /// <returns>string</returns>
        public static string UrlButton(this HtmlHelper helper, string value,
            string url, string className, string confirmInfo, bool isDisabled) {
            string s = "<input type=\"button\" value=\"{0}\"{2} {4} onclick=\"$c.go('{1}'{3});\" />";
            return string.Format(s, value, url,
                string.IsNullOrEmpty(className) ? string.Empty : string.Format(" class=\"{0}\"", className),
                string.IsNullOrEmpty(confirmInfo) ? string.Empty : string.Format(",'{0}'", confirmInfo),
                isDisabled ? " disabled=\"disabled\"" : string.Empty);
        }

        #endregion       

    }
}
